package com.tanhua.dubbo.server.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


/*
    使用redis的自增长的类型，实现自增长的id
 */
@Service
public class IdService {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成自增长的Id
     *
     * @param type
     * @param objectId
     * @return
     */
    public Long createId(String type, String objectId) {
        //如果objectId已经存在,就返回对应的id


        //将type转换成大写
        type = StringUtils.upperCase(type);  //统一ID

        String idHashKey = "TANHUA_ID_HASH_" + type;
        //判断objectid是否存在
        if (redisTemplate.opsForHash().hasKey(idHashKey, objectId)) {
            return Long.valueOf(redisTemplate.opsForHash().get(idHashKey, objectId).toString());
        }

        String idKey = "TANHUA_ID_" + type;
        Long id = redisTemplate.opsForValue().increment(idKey);

        //将生成的id写入到hash表中
        redisTemplate.opsForHash().put(idHashKey, objectId, id.toString());

        return id;
    }

}
